/**
 * 重复执行指定函数
 * @param {number} times 执行次数
 * @param {function} callback 回调函数
 */
export const doCustomTimes = (times, callback) => {
  let i = -1
  while (++i < times) {
    callback()
  }
}

/**
 * 获取最大数组项
 * @param {Array} arr 数组
 * @param {function} callback 回调函数
 */
export const getMax = (arr, callback) => {
  let i = 0
  arr.forEach(element => {
    let val = callback(element)
    if (!i || i < val) i = val
  });
  return i
}

/**
 * 图片压缩
 * @param {string} url 图片地址
 * @param {number}} width 目标图片宽度
 */
export function imageCompress(url, width) {
  let img = document.createElement('img')
  img.src = url
  let scale = img.width / img.height

  let canvas = document.createElement("canvas")
  let twidth = width
  let theight = ~~(width / scale)

  canvas.width = twidth
  canvas.height = theight
  var context = canvas.getContext("2d")
  context.drawImage(img, 0, 0, img.width, img.height, 0, 0, twidth, theight)
  return canvas.toDataURL("image/jpeg")
}

/**
 * 函数节流
 * @param {function} fn 需要执行的函数
 * @param {object} context 上下文
 * @param {number}} delay 延迟时间
 * @param {obj} text 参数
 */
export function throttle(fn, context, delay = 500, obj) {
  clearTimeout(fn.timer);
  fn._cur = Date.now();  //记录当前时间

  fn.timer = setTimeout(function () {
    fn.call(context, obj);
  }, delay)
}



